import axios from 'axios';
import env from '../../build/env';
import Cookies from 'js-cookie';
import ViewUI from 'view-design';

// 本地测试地址 http://192.168.17.134/api/
// 线上测试地址 http://39.100.126.32/api/
let util = {
	baseURL: env === 'development' ? 'http://39.100.126.32' : 'http://39.100.126.32'
};

util.title = function (title) {
    title = title ? '小折 - ' + title : '小折';
    window.document.title = title;
};

util.ajax = axios.create({
    baseURL: util.baseURL,
    params: {},
    headers: {
        // Timestamp : parseInt(new Date().getTime() / 1000)
    },
    timeout: 30000
});

// 请求拦截器
util.ajax.interceptors.request.use(
    config => {
    	// token
        if(Cookies.get('token')) {
        	config.data['access_token'] = Cookies.get('token');
        }
        // 用户id
        if(Cookies.get('user_id')) {
        	config.data['current_custom_id'] = Cookies.get('user_id');
        }
        // iview_ui loading bar
        ViewUI.LoadingBar.start();
        return config;
    }
);

// 响应拦截器
util.ajax.interceptors.response.use(
    response => {
    	ViewUI.LoadingBar.finish();
        if(response.data.code !== 200) {
        	ViewUI.Message.error(response.data.message);
            return Promise.reject();
        }
        return response.data.result;
    },
    error => {
    	ViewUI.LoadingBar.error();
    	// ViewUI.Message.error('网络错误');
        return Promise.reject();
    }
);

export default util;
